import { defineStore } from 'pinia'

const userStr = sessionStorage.getItem('sysUser')
const permissionsStr = sessionStorage.getItem('permissions')
const sysUser = userStr ? JSON.parse(userStr) : {}

const useUserStore = defineStore('user', {
  state: () => ({
    user: sysUser,
    permissions: JSON.parse(permissionsStr || '{}'),
  }),
  actions: {
    setUser(data: any) {
      if (!data.user.avatar) {
        data.user.avatar = 'http://vue.ruoyi.vip/static/img/profile.473f5971.jpg'
      }
      const permissions: any = {}
      data.permissions.forEach((item: string) => {
        const arr = item.split(':')
        if (arr.length > 2) {
          const key = arr[0] + arr[1]
          if (!permissions[key]) {
            permissions[key] = []
          }
          permissions[key].push(arr[2])
        }
      })
      sessionStorage.setItem('sysUser', JSON.stringify(data.user))
      sessionStorage.setItem('roles', JSON.stringify(data.roles))
      sessionStorage.setItem('permissions', JSON.stringify(permissions))
      this.user = data.user
      this.permissions = permissions
    },
  },
})

export default useUserStore
